﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class Admin_Components_MasterData_Promotion : System.Web.UI.UserControl
{
    DBDataContext db = LINQUtil.GetDBWriteOnly();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            loadForm();

            dtpFromDate.SelectedDate = DateTime.Now.Date;
            dtpFromDate.MinDate = DateTime.Now;

            dtpToDate.SelectedDate = DateTime.Now.Date.AddMonths(1);
            dtpToDate.MinDate = DateTime.Now;
            
            gv.Visible = false;
        }
    }
    private void loadForm()
    {
        Utils.LoadCodeDetail(cboPromotionType, "PromotionType", 0);
        Utils.loadProductGifToCombo(cboProduct);
        Utils.LoadCodeDetail(cboWeight, "PackType", 0);
        Utils.LoadCodeDetail(cboPromotionStatusSearch, "PromotionStatus", 1);
        Utils.LoadCodeDetail(cboPromotionTypeSearch, "PromotionType", 1);
        Utils.LoadCodeDetail(cboPromotionStatus, "PromotionStatus", 1);
        cboPromotionStatus.Enabled = false;

        PrmotionAmount.Visible = false;
        gvData.Columns[5].Display = false;
        gvData.DataSource = new DataTable();
        gvData.DataBind();
    }


    private DataTable createDataTable()
    {
        DataTable dt = new DataTable();
        if (ViewState["CurrentTable"] == null)
        {
            dt.Columns.Add("ProductID");
            dt.Columns.Add("ProductName");
            dt.Columns.Add("Weight");
            dt.Columns.Add("ProductWeight");
            dt.Columns.Add("Quantity");
            ViewState["CurrentTable"]= dt;
        }
        else
        {
            dt = (DataTable)ViewState["CurrentTable"];
        }
        return dt;
    }
    
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            string productID = cboProduct.SelectedValue;
            string productName = cboProduct.SelectedItem.Text;
            string weight = cboWeight.SelectedValue;
            string ProductWeight = cboWeight.SelectedItem.Text;
            string promotionType = cboPromotionType.SelectedValue;
            DataTable dt = createDataTable();
            if (productID != "")
            {
                if (ViewState["CurrentTable"] != null)
                {
                    if (promotionType.ToLower() == "k")
                    {
                        if (dt.Select("ProductID='" + productID + "'").Count() > 0)
                        {
                            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Quà tặng: " + productName + " đã tồn tại. vui lòng chọn sp khác");
                            return;
                        }
                    }
                    else if (promotionType.ToLower() == "p")
                    {
                        if (dt.Select("ProductID='" + productID + "' AND Weight=" + weight).Count() > 0)
                        {
                            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Quà tặng: " + productName +" - "+ProductWeight+ " đã tồn tại. vui lòng chọn quà tặng khác");
                            return;
                        }
                    }

                    var pro = (from p in db.Products
                               where p.ID == Convert.ToInt32(productID)
                               && p.Status == 'A' && p.ProductType == "P"
                               select p).FirstOrDefault();
                    if (pro != null)
                    {
                        DataRow drNew = dt.NewRow();
                        drNew["ProductID"] = pro.ID;
                        drNew["ProductName"] = productName;
                        drNew["Weight"] = weight;
                        drNew["ProductWeight"] = ProductWeight;

                        dt.Rows.Add(drNew);

                    }
                    ViewState["CurrentTable"] = dt;

                    if (dt.Rows.Count > 2)
                    {
                        RadPageView2.Height = 330;
                        gvData.Height = 250;
                        gvData.ClientSettings.Scrolling.AllowScroll = true;
                    }
                   
                    gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                    gvData.DataSource = dt;
                    gvData.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Promotion-btnAdd_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void grvData_ItemCommand(object sender, GridCommandEventArgs e)
    {
        string commandName = e.CommandName;
        if (commandName == "EditDelItem")
        {

            string ProductID = e.CommandArgument.ToString();
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow[] rows = dt.Select("ProductID=" + ProductID);
            foreach (DataRow r in rows)
            {
                r.Delete();
            }
            ViewState["CurrentTable"] = dt;
            gvData.DataSource = dt;
            gvData.DataBind();
        }
    }
    protected void cboPromotionType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        string PromotionType = this.cboPromotionType.SelectedValue;
        ViewState["CurrentTable"] = null;
        gvData.DataSource = new DataTable();
        gvData.DataBind();
        setForm(PromotionType);
    }

    private void setForm(string PromotionType,bool isFirst = true)
    {
        if (PromotionType == "M") // theo tien
        {
            // TabStrip1.SelectedIndex = 0;
            // RadPageView2.Selected = true;
            RadPageView2.Visible = false;
            TabStrip1.Tabs[1].Visible = false;
            PrmotionAmount.Visible = true;
            RadPageView1.Height = 200;
            txtDiscount.Enabled = true;
            txtAmount.Enabled = true;
        }
        else
        {
            txtDiscount.Enabled = false;
            txtAmount.Enabled = false;
            RadPageView2.Visible = true;
            TabStrip1.Tabs[1].Visible = true;
            PrmotionAmount.Visible = false;
            RadPageView1.Height = 200;
            if (PromotionType == "P")
            {

                gvData.Columns[5].Display = true;
                gvData.Columns[4].HeaderText = "Loại vỏ bao";
            }
            else
            {

                gvData.Columns[4].HeaderText = "Loại quà tặng";
                gvData.Columns[5].Display = false;
            }
            if (isFirst)
            {
                gvData.DataSource = new DataTable();
                gvData.DataBind();
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string PromotionType = this.cboPromotionType.SelectedValue;
            string PromotionName = this.txtPromotionName.Text.Trim();

            if (PromotionType != "M")
            {
                if (gvData.Items.Count <= 0)
                {
                    RadPageView2.Enabled = true;
                    TabStrip1.SelectedIndex = 1;
                    RadPageView2.Selected = true;

                    JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng chọn chi tiết khuyến mãi!");
                    return;
                }     
            }
            if (PromotionType == "P")
            {
                foreach (GridDataItem it in gvData.Items)
                {
                    RadNumericTextBox QuantitySelect = (RadNumericTextBox)it.FindControl("txtQuantity");
                    int Quantity = int.Parse(QuantitySelect.Text == "" ? "0" : QuantitySelect.Text);
                    if (Quantity <= 0)
                    {
                        JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập số lượng tại sản phẩm " + it["ProductName"].Text);
                        QuantitySelect.Focus();
                        return;
                    }
                }
            }
            //Update record cu
            if (ViewState["PromotionID"] == null)
            {
                var proObj = db.Promotions.FirstOrDefault<Promotion>(p => p.PromotionType == PromotionType && p.Status == 'A');
                if (proObj != null)
                {
                    proObj.Status = 'I';
                    proObj.LastUpdatedBy = Session["UserName"].ToString();
                    proObj.LastUpdatedDateTime = DateTime.Now;
                    proObj.EndDate = dtpFromDate.SelectedDate.Value.AddDays(-1);
                    db.Update<Promotion>(proObj);
                }
            }
            else if (ViewState["PromotionID"] != null)
            {
                var proDel = db.Promotions.First<Promotion>(p => p.ID == int.Parse(ViewState["PromotionID"].ToString()));
                if (proDel != null)
                {
                    db.Delete<Promotion>(proDel);
                    var list = (from detail in db.PromotionDetails where detail.PromotionID == int.Parse(ViewState["PromotionID"].ToString()) select detail).ToList();
                    db.Delete<PromotionDetail>(list);
                }
            }
            if (PromotionType == "M")//Theo so tien
            {

                //Insert Record moi
                Promotion pro = new Promotion();
                string Amount = txtAmount.Text.Replace(",", "");
                string Discount = txtDiscount.Text.Replace(",", "");

                pro.PromotionName = PromotionName;
                pro.PromotionType = PromotionType;
                pro.StartDate = dtpFromDate.SelectedDate;
                pro.EndDate = dtpToDate.SelectedDate;

                pro.Status = 'A';
                pro.CreatedBy = Session["UserName"].ToString();
                pro.LastUpdatedBy = Session["UserName"].ToString();
                pro.CreatedDateTime = DateTime.Now;
                pro.LastUpdatedDateTime = DateTime.Now;

                db.Insert<Promotion>(pro);
                db.SubmitChanges();

                PromotionDetail proDetail = new PromotionDetail();
                proDetail.PromotionID = pro.ID;
                proDetail.DiscountAmount = double.Parse(Discount);
                proDetail.Amount = double.Parse(Amount);
                proDetail.Status = 'A';
                proDetail.CreatedBy = Session["UserName"].ToString();
                proDetail.LastUpdatedBy = Session["UserName"].ToString();
                proDetail.CreatedDateTime = DateTime.Now;
                proDetail.LastUpdatedDateTime = DateTime.Now;

                db.Insert<PromotionDetail>(proDetail);
                db.SubmitChanges();
            }
            else
            {

                //Insert Record moi
                Promotion pro = new Promotion();

                pro.PromotionName = PromotionName;
                pro.PromotionType = PromotionType;
                pro.StartDate = dtpFromDate.SelectedDate;
                pro.EndDate = dtpToDate.SelectedDate;

                pro.Status = 'A';
                pro.CreatedBy = Session["UserName"].ToString();
                pro.LastUpdatedBy = Session["UserName"].ToString();
                pro.CreatedDateTime = DateTime.Now;
                pro.LastUpdatedDateTime = DateTime.Now;

                db.Insert<Promotion>(pro);
                db.SubmitChanges();

                List<PromotionDetail> list = new List<PromotionDetail>();
                foreach (GridDataItem it in gvData.Items)
                {
                    int ProductID = int.Parse(it["ProductID"].Text);
                    int Weight = int.Parse(it["Weight"].Text.Replace(",", ""));

                    PromotionDetail proDetail = new PromotionDetail();
                    proDetail.PromotionID = pro.ID;
                    proDetail.ProductID = ProductID;
                    if (PromotionType == "K")
                    {
                        proDetail.Weight = Weight;
                    }
                    else
                    {
                        RadNumericTextBox QuantitySelect = (RadNumericTextBox)it.FindControl("txtQuantity");
                        int Quantity = int.Parse(QuantitySelect.Text);

                        proDetail.PackType = Weight.ToString();
                        proDetail.PackQuantity = Quantity;
                    }
                    proDetail.Status = 'A';
                    proDetail.CreatedBy = Session["UserName"].ToString();
                    proDetail.LastUpdatedBy = Session["UserName"].ToString();
                    proDetail.CreatedDateTime = DateTime.Now;
                    proDetail.LastUpdatedDateTime = DateTime.Now;

                    list.Add(proDetail);
                }
                db.Insert<PromotionDetail>(list);
                db.SubmitChanges();
                if (ViewState["PromotionID"] != null)
                {
                    this.txtPromotionNameSearch.Text = txtPromotionName.Text;
                    LoadData();
                    gv.DataBind();
                    this.txtPromotionNameSearch.Text = "";
                }
                ViewState["PromotionID"] = pro.ID;
                cboPromotionStatus.SelectedValue = "A";
            }

            CacheUtil.ClearCache("ListProductPromotion");
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");
            this.btnSave.Enabled = false;
        }
        catch (Exception ex)
        {
            this.btnSave.Enabled = true;
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Promotion-btnSave_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (ViewState["PromotionID"] != null)
        {
           int promotionID = int.Parse(ViewState["PromotionID"].ToString());
           cboPromotionStatus.SelectedValue = "E";
           CancelPromotion(promotionID);
        }
    }

    private void CancelPromotion(int PromotionID)
    {
        try
        {
            var pro = db.Promotions.FirstOrDefault<Promotion>(p => p.ID == PromotionID);
            if (pro != null)
            {
                pro.Status = 'E';
                pro.CreatedBy = Session["UserName"].ToString();
                pro.LastUpdatedBy = Session["UserName"].ToString();
                pro.CreatedDateTime = DateTime.Now;
                pro.LastUpdatedDateTime = DateTime.Now;
                db.Update<Promotion>(pro);
                db.SubmitChanges();
            }
            CacheUtil.ClearCache("ListProductPromotion");
            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công!");
        }
        catch (Exception ex)
        {
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("Promotion-CancelPromotion");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Promotion", false);
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        LoadData();
        gv.DataBind();
    }

    protected void gv_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        if (RadMultiPag1.SelectedIndex == 2)//Tab tim kiem
        {
            LoadData();
        }
    }
    protected void gv_ItemCommand(object sender, GridCommandEventArgs e)
    {
         string commandName = e.CommandName;
         string promotionID = e.CommandArgument.ToString();
         if (commandName == "EditDelItem")
         {
             CancelPromotion(int.Parse(promotionID));
             LoadData();
             gv.DataBind();
         }
         else if (commandName == "DetailItem")
         {
             RadPageView1.Selected = true;
             TabStrip1.SelectedIndex = 0;
             var pro = db.Promotions.First<Promotion>(p => p.ID == int.Parse(promotionID));
             if (pro != null)
             {
                 ViewState["PromotionID"] = promotionID;
                 this.txtPromotionName.Text = pro.PromotionName;
                 this.cboPromotionType.SelectedValue = pro.PromotionType;
                 this.dtpFromDate.MinDate = DateTime.Now.AddYears(-30);
                 this.dtpFromDate.Enabled = true;

                 this.dtpToDate.MinDate = DateTime.Now.AddYears(-30);
                 this.dtpToDate.Enabled = true;

                 this.dtpFromDate.SelectedDate = pro.StartDate;
                 this.dtpToDate.SelectedDate = pro.EndDate;
                 cboPromotionType.Enabled = false;
                 cboPromotionStatus.SelectedValue = pro.Status.ToString();
                 if (pro.Status != 'A')
                 {
                     this.btnSave.Visible = false;
                     this.btnCancel.Visible = false;
                 }
                 else
                 {
                     this.btnSave.Visible = true;
                     this.btnCancel.Visible = true;
                     this.btnSave.Enabled = true;
                 }
                 setForm(pro.PromotionType,false);

                 if (pro.PromotionType != "M")
                 {
                     //chi tiet
                     var listDetail = (from detail in db.PromotionDetails
                                       join p in db.Products on detail.ProductID equals p.ID
                                       where detail.PromotionID == int.Parse(promotionID)
                                       select new
                                       {
                                           ProductID = detail.ProductID,
                                           ProductName = p.ProductName,
                                           Weight = detail.Weight,
                                           ProductWeight = (detail.Weight == null || detail.Weight == 0) ? detail.PackType : detail.Weight.ToString() + " kg",
                                           Quantity = detail.PackQuantity
                                       }).ToList();
                     if (listDetail.Count > 2)
                     {
                         RadPageView2.Height = 230;
                         gvData.Height = 150;
                         gvData.ClientSettings.Scrolling.AllowScroll = true;
                     }
                     gvData.ClientSettings.Scrolling.UseStaticHeaders = true;
                     gvData.DataSource = listDetail;
                     gvData.DataBind();
                     ViewState["CurrentTable"] = listDetail.ToDataTable();
                    
                 }
                 else
                 {
                     var detail = db.PromotionDetails.First<PromotionDetail>(d => d.PromotionID == int.Parse(promotionID));
                     this.txtAmount.Text = detail.Amount.ToString();
                     this.txtDiscount.Text = detail.DiscountAmount.ToString();
                 }
             }
         }
    }
    protected void gv_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = (GridDataItem)e.Item;
            string status = item["Status"].Text.ToString();
            Button DeleteCol = (Button)item.FindControl("btnDelete");
            if (status != "Còn hiệu lực")
            {
                DeleteCol.Visible = false;
            }
        }
    }
    private void LoadData()
    {
        gv.Visible = true;
        string promotionNme = this.txtPromotionNameSearch.Text;
        string status = this.cboPromotionStatusSearch .SelectedValue;
        string promotionType = this.cboPromotionTypeSearch.SelectedValue;
        var q = (from pro in db.Promotions
                      join code in db.CodeDetails on pro.Status.ToString() equals code.CDCode
                      join code1 in db.CodeDetails on pro.PromotionType.ToString() equals code1.CDCode
                      where (pro.PromotionName.IndexOf(promotionNme) >= 0 || promotionNme == "")
                      && (pro.Status.ToString() == status || status == "" || (status == "A" && pro.EndDate >= DateTime.Now.Date) || (status == "I" && pro.EndDate < DateTime.Now.Date))
                      && (pro.PromotionType == promotionType || promotionType == "")
                      && (pro.StartDate >= (this.rtpFromDateSearch.SelectedDate.HasValue==true?this.rtpFromDateSearch.SelectedDate:DateTime.Now.AddYears(-30) ) && pro.EndDate <= (rtpToDateSearch.SelectedDate.HasValue?rtpToDateSearch.SelectedDate:DateTime.Now.AddYears(50)))
                      && code.CMCode.ToString() == "PromotionStatus"
                      && code1.CMCode.ToString() == "PromotionType"
                      orderby pro.Status
                      select new
                      {
                          PromotionID = pro.ID,
                          PromotionName = pro.PromotionName,
                          ProductType = code1.CDName,
                          StartDate = pro.StartDate,
                          EndDate = pro.EndDate,
                          Status = ((code.CDCode == "A" && pro.EndDate < DateTime.Now.Date)?"Hết hiệu lực": code.CDName),
                          StatusCode = code.CDCode
                      }).ToList();
         if (q.Count > 0)
            {
                gv.Height = 280;
                gv.ClientSettings.Scrolling.AllowScroll = true;
                gv.ClientSettings.Scrolling.UseStaticHeaders = true;
                gv.VirtualItemCount = q.Count;
                gv.DataSource = q;
            }
            else
            {
                gv.DataSource = new DataTable();
            }
    }
}